<?php

namespace addons\yungift\model;

use addons\yungift\library\ModelTrait;
use fast\Tree;
use think\Cache;
use think\Model;
use traits\model\SoftDelete;

/**
 * 分组模型
 */
class Group extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yungift_group';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    public function scopeShow($query)
    {
        return $query->where('status', '=', self::STATUS_NORMAL);
    }

    // 状态
    const STATUS_NORMAL = 1;
    const STATUS_HIDDEN = 2;

    public static function getStatusList()
    {
        return [self::STATUS_NORMAL => __('Normal'), self::STATUS_HIDDEN => __('屏蔽')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? '';
    }

    // 上级分组
    public function parentData()
    {
        return $this->hasOne(Group::class, 'id', 'parent_id');
    }

    // 获取分类树
    public static function getTreeList()
    {
        $groupList = Group::where([])->select();

        Tree::instance()->init($groupList, 'parent_id');
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));

        return $groupList;
    }

    // 获取分类列表 - 树型
    public static function getTreeMap()
    {
        $groupList = self::getTreeList();
        $groupMap = [];
        foreach ($groupList as $item) {
            $groupMap[$item['id']] = $item['name'];
        }

        return $groupMap;
    }

    // 获取分类列表 - 选择
    public static function getTreeSelect($selected = [])
    {
        $treeList = self::getTreeList();
        $resultList = [];
        foreach ($treeList as $item) {
            $resultList[] = [
                'id'     => $item['id'],
                'parent' => $item['parent_id'] ?: '#',
                'text'   => __($item['name']),
                'type'   => 'menu',
                'state'  => ['selected' => in_array($item['id'], $selected) && ! $item['haschild']]
            ];
        }

        return $resultList;
    }

    // 获取分类列表 - 树型
    public static function getRelationIds($groupId)
    {
        $relationIds = [];
        if ($groupData = Group::get(['id' => $groupId])) {
            $relationIds = Group::where('levels', 'like', $groupData['levels'] . '-' . $groupData['id'] . '%')
                ->column('id');
        }
        array_unshift($relationIds, $groupData['id']);

        return $relationIds;
    }

    // 获取分类列表 - 树型
    public static function getUserLevelGroups($memberGroupId, $groupIds = [], $hasAll = true)
    {
        $levelGroups = [];
        if ($groupData = Group::get(['id' => $memberGroupId])) {
            $levels = explode('-', $groupData->levels);
            $levels[] = $groupData['id'];
            $count = count($levels);
            $groupList = Group::field(['id, parent_id, levels, name'])->select();
//            $groupList = Cache::remember('groupList:all', function () {
//                return Group::field(['id, parent_id, levels, name'])->select();
//            }, 5);
            if ($groupIds) {
                foreach ($groupList as $key => $item) {
                    if (! in_array($item['id'], $groupIds)) {
                        unset($groupList[$key]);
                    }
                }
            }
            for ($i = $count - 1; $i >= 1; $i--) {
                $level = implode('-', array_slice($levels, 0, $i + 1));
                $childGroupIds = [];
                $parentGroup = null;
                foreach ($groupList as $item) {
                    if (strpos($item['levels'], $level . '-') === 0 || $item['levels'] === $level) {
                        $childGroupIds[] = $item['id'];
                    }
                    if ($item['id'] == $levels[$i]) {
                        $parentGroup = $item;
                    }
                }
                array_unshift($childGroupIds, $parentGroup['id']);
                $levelGroups[$parentGroup['id']] = [
                    'id'       => $parentGroup['id'],
                    'name'     => $parentGroup['name'],
                    'childIds' => $childGroupIds
                ];
            }
        }
        if ($hasAll) {
            $levelGroups[0] = [
                'id'       => 0,
                'name'     => '全部',
                'childIds' => $groupIds
            ];
        }

        return $levelGroups;
    }
}
